<?php


namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UploadController extends CommonController
{
    private $GetUploadConf;
    public function __construct()
    {
        $this->GetUploadConf = new ConfigController();
    }

    //上传至七牛云
    public function upload(Request $request){
        $file=$request->file();
        $size=ceil($file['file']->getSize()/1024); //获取kb
        $size=ceil($size/2048);
        if ($size>2){
            return $this->ReturnJson(-1,'上传不能超过2MB','');
        }
        $rule = ['jpg', 'png', 'gif','jpeg'];
        $upload_type=$this->GetUploadConf->GetUploadConf();
        switch ($upload_type){
            case 2:
//                七牛云上传
                $auth=new Auth(config('app.QINIU_ACCESSKEY'),config('app.QINIU_SECRETKEY'));
                $token = $auth->uploadToken(config('app.QINIU_BUCKET'));
                $filePath = $file['file']->getRealPath();
                $getClientOriginalExtension = $file['file']->getClientOriginalExtension();
                if (!in_array($getClientOriginalExtension, $rule)) {
                    return $this->ReturnJson(-1,'图片格式为jpg,png,gif','');
                }
                $date = time();
                $key = $date.'.'.$getClientOriginalExtension;
                $uploadMgr = new UploadManager();
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

                if ($err !== null) {
                    return $this->ReturnJson(-1,'上传失败','');
                } else {
                    $back_url= config('app.QINIU_domain').'/'.$ret['key'];
                    return $this->ReturnJson(200,'上传成功',['url'=>$back_url]);
                }
            case 1:
                //本地上传
                $url_path = 'uploads/local';
                $clientName = $file['file']->getClientOriginalName();
                $entension = $file['file']->getClientOriginalExtension();
                if (!in_array($entension, $rule)) {
                    return $this->ReturnJson(-1,'图片格式为jpg,png,gif','');
                }
                $newName = md5(date("Y-m-d H:i:s") . $clientName) . "." . $entension;
                $file['file']->move($url_path, $newName);
                $namePath =config('app.LOCAL_domain').'/'.$url_path . '/' . $newName;
                return $this->ReturnJson(200,'上传成功',['url'=>$namePath]);
        }


    }

}
